package com.qbccn.oauth2service.service.impl;

import com.qbccn.oauth2service.domain.SsoRole;
import com.qbccn.oauth2service.domain.SsoUser;
import com.qbccn.oauth2service.dto.MenuList;
import com.qbccn.oauth2service.dto.UserInfo;
import com.qbccn.oauth2service.mapper.SsoMenuMapper;
import com.qbccn.oauth2service.mapper.SsoRoleMapper;
import com.qbccn.oauth2service.mapper.SsoUserMapper;
import com.qbccn.oauth2service.service.RedisService;
import com.qbccn.oauth2service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SsoUserMapper ssoUserMapper;
    @Autowired
    private SsoRoleMapper ssoRoleMapper;
    @Autowired
    private SsoMenuMapper ssoMenuMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public SsoUser getUserInfo(String username) {
        return ssoUserMapper.getUserInfo(username);
    }

    @Override
    public UserInfo info(String username) {
        UserInfo info = (UserInfo) redisService.get("info:" + username);
        if (info != null) {
            return info;
        } else {
            info = ssoUserMapper.getInfo(username);
            redisService.set("info:" + username, info, 60 * 60 * 4);
            return info;
        }
    }

    @Override
    public List<SsoRole> getRoleByUserId(Integer userId) {
        return ssoRoleMapper.getRoleByUserId(userId);
    }

    @Override
    public List<MenuList> getUserMenu(String username, String pertainSystem) {
        List<MenuList> redis = (List<MenuList>) redisService.get("menu:" + username);
        if (redis!=null && !redis.isEmpty()) {
            return redis;
        } else {
            List<MenuList> res = ssoMenuMapper.getMenuList(username, pertainSystem);
            //存储12小时，key=menu_工号
            redisService.set("menu:" + username, res, 60 * 60 * 12);
            return res;
        }
    }
}
